var lightUp = true;
var layout = 'left';
(function ($) {
    'use strict';

    var defaultSidebar = $('<div class="default-sidebar"></div>');
    var horizontalMenu = $('<div class="horizontal-menu"></div>');

    loadTranslateMap('/webjars/json/translate_zh.json,/webjars/json/translate_en.json', function () {
        axiosPost({
            url: "/schedule/permission/checkPermission",
            success: function (json) {
                loadMenu('/webjars/json/menu.json', function () {
                    loadPageHeader();
                    loadPageContent();
                    $(".off-sidebar").load(contentPath + '/webjars/html/base/offsidebar.htm', function () {
                        handleOffsidebar();
                        $(".offcanvas-scroll").niceScroll({
                            railpadding: {
                                top: 0,
                                right: 2,
                                left: 0,
                                bottom: 0
                            },
                            scrollspeed: 100,
                            zindex: "auto",
                            hidecursordelay: 800,
                            cursorwidth: "5px",
                            cursorcolor: "rgba(52, 40, 104, 0.1)",
                            cursorborder: "rgba(52, 40, 104, 0.1)",
                            preservenativescrolling: true,
                            boxzoom: false
                        });
                    }).on('click', function (event) {
                        if ($(event.target).is('.off-sidebar') || $(event.target).is('.off-sidebar-close')) {
                            $('.off-sidebar').removeClass('is-visible');
                            event.preventDefault();
                        }
                    });
                    $(window).resize(function () {
                        $('.auto-scroll').height($(window).height() - 124);
                        resizeContentWithNiceScroll();
                        textEllipsis();
                        dataTableNiceScroll();
                        adjustPosition();
                        resizeModalWithNiceScroll();
                    });
                    $(window).trigger('resize');
                    $(".preloader").delay(350).fadeOut("slow");
                });
            }
        });
    });

    function loadPageHeader() {
        var nav = $('<nav class="navbar"></nav>');
        var navHeader = $('<div class="navbar-header"></div>').append($('<span class="navbar-brand">分布式调度管理系统</span>'));
        nav.append($('<div class="navbar-holder d-flex align-items-center align-middle justify-content-between"></div>').append(navHeader).append(createNavMenu()));
        if (layout == 'left') {
            navHeader.append($('<a id="toggle-btn" href="javascript:void(0)" class="menu-btn active"><span></span><span></span><span></span></a>').on('click', function (e) {
                e.preventDefault();
                $(this).toggleClass('active');
                var sideNavbar = $('.side-navbar').toggleClass('shrinked');
                $('.content-inner').toggleClass('active');
                if ($('#toggle-btn').hasClass('active')) {
                    if ($(window).outerWidth() > 1183) {
                        $('.navbar-header .brand-small').hide();
                        $('.navbar-header .brand-big').show();
                    }
                    sideNavbar.find('a').unbind('mouseenter').unbind('mouseleave');
                } else {
                    if ($(window).outerWidth() > 1183) {
                        $('.navbar-header .brand-small').show();
                        $('.navbar-header .brand-big').hide();
                    }
                    sideNavbar.find('a').each(function () {
                        var $this = $(this);
                        createTitle($this, {
                            direction: 'right', bodyStyle: 'height:40px', bodyContent: function () {
                                return $this.find('span:first').text()
                            }, left: 70, top: function () {
                                return $this.offset().top
                            }
                        });
                    });
                }
                if ($(window).outerWidth() < 1183) {
                    $('.navbar-header .brand-small').show();
                }
                textEllipsis();
                dataTableNiceScroll();
            }));
            $('.header').empty().append(nav.addClass('fixed-top'));
            $('.page').removeClass('db-modern');
        } else {
            $('.header').empty().append($('<div class="container"></div>').append(nav));
            $('.page').removeClass('db-modern').addClass('db-modern');
        }
    }

    function loadPageContent() {
        $(".page-content").append($('<div class="content-inner" id="contentInner"><div class="container-fluid" id="containerFluid"><div class="row" id="tabBar"><div class="page-header" id="pageHeader"></div></div></div></div>'))
            .before($('<a href="javascript:void(0)" class="go-down"><i class="la la-arrow-down"></i></a>'))
            .after($('<a href="javascript:void(0)" class="go-top"><i class="la la-arrow-up"></i></a>'));
        var tabBar_back = $('<div class="iconBtn translate float-left mr-2 disabled" id="tabBarBack" style="margin-top:-2px" translateFor="text.tabBarBack" translateTo="popoverTitle" ><i class="ion ion-arrow-left-a tabBar"></i></div>').on('click', function(){pageHistory(-1)});
        var tabBar_forward = $('<div class="iconBtn translate float-left mr-2 disabled" id="tabBarForward" style="margin-top:-2px" translateFor="text.tabBarForward" translateTo="popoverTitle" ><i class="ion ion-arrow-right-a tabBar" style="margin-left:3px"></i></div>').on('click', function(){pageHistory(1)});
        var tabBar_refresh = $('<div class="iconBtn translate float-left mr-3" style="margin-top:-2px" translateFor="text.tabBarRefresh" translateTo="popoverTitle" ><i class="ion ion-refresh tabBar"></i></div>').on('click', function(){contentRefresh()});
        createTitleWithIconBtn($('#pageHeader').append(tabBar_back).append(tabBar_forward).append(tabBar_refresh).append($('<div id="tabBarHeader" class="float-left"></div>')));
        translate($('#tabBar'));
        $('.go-down').click(function (event) {
            event.preventDefault();
            var content = $("#content");
            content && content.animate({scrollTop: content[0].scrollHeight - $(window).height() + 140}, 800)
        });
        $('.go-top').click(function (event) {
            event.preventDefault();
            $("#content").animate({scrollTop: 0}, 800)
        });
        showGoDown();
        loadPageSidebar(true);
    }

    function loadPageSidebar(isRedirect) {
        if (layout == 'left') {
            loadLeftSidebar(isRedirect);
        } else {
            loadTopSidebar(isRedirect);
        }
        setTimeout(function () {
            resizeContentWithNiceScroll();
            resizeModalWithNiceScroll(false);
        }, 500);
    }

    function createNavMenu() {
        var navMenu = $('<ul class="nav-menu list-unstyled d-flex flex-md-row align-items-md-center pull-right"></ul>');
        var navItem1 = $('<li class="nav-item"></li>').append($('<a href="javascript:void(0);" class="open-sidebar"><i class="la la-ellipsis-h"></i></a>').on('click', function (event) {
            event.preventDefault();
            $('.off-sidebar').addClass('is-visible');
        }));
        return navMenu.append(navItem1);
    }

    function loadLeftSidebar(isRedirect) {
        var sidebar = $('<nav class="side-navbar box-scroll sidebar-scroll"></nav>');
        var ul = getLeftSidebarUl();
        $.each(menu, function (i, item) {
            if (item.header == true) {
                sidebar.append(ul).append($('<span class="heading translate" translateFor="menu.' + item.name + '"></span>'));
                ul = getLeftSidebarUl();
            } else {
                if (item.childs != undefined && item.childs != null) {
                    ul.append(createLeftSidebarDropdown(item, isRedirect));
                } else {
                    ul.append(createRedirect(item, isRedirect));
                }
            }
        });
        $('#contentInner').removeClass('boxed');
        $('#containerFluid').removeClass("horizontal");
        $("#tabBar").removeClass('container m-auto');
        $("#content").removeClass('container m-auto');
        horizontalMenu.detach();
        $(".page-content").addClass("d-flex align-items-stretch").prepend(defaultSidebar.empty().append(sidebar.append(ul)));
        translate(sidebar);
        sidebar.niceScroll({
            cursorcolor: "transparent",
            cursorborder: "transparent",
            cursoropacitymax: 0,
            boxzoom: false,
            autohidemode: "hidden",
            cursorfixedheight: 80
        });
    }

    function loadTopSidebar(isRedirect) {
        var sidebar = $('<nav class="navbar navbar-light navbar-expand-lg main-menu"></nav>');
        var navbarCollapse = $('<div class="collapse navbar-collapse"></div>');
        var ul = $('<ul class="navbar-nav mr-auto"></ul>');
        $.each(menu, function (i, item) {
            if (!item.header) {
                if (item.childs != undefined && item.childs != null) {
                    ul.append(createTopSidebarDropdown(item, isRedirect));
                } else {
                    ul.append(createRedirect(item, isRedirect));
                }
            }
        });
        $('#contentInner').addClass("boxed");
        $('#containerFluid').addClass("horizontal");
        $("#tabBar").addClass('container m-auto');
        $("#content").addClass('container m-auto');
        defaultSidebar.detach();
        $(".page-content").removeClass("d-flex align-items-stretch").prepend(horizontalMenu.empty().append($('<div class="container"></div>').append($('<div class="row"></div>').append(sidebar.append(navbarCollapse.append(ul))))));
        translate(sidebar);
    }

    function getLeftSidebarUl() {
        return $('<ul class="list-unstyled"></ul>');
    }

    function createLeftSidebarDropdown(item, isRedirect) {
        var id = "dropdown-" + item.name;
        var subul = $('<ul id="' + id + '" class="collapse list-unstyled pt-0"></ul>');
        $.each(item.childs, function (subI, subItem) {
            if (subItem.childs != undefined && subItem.childs != null) {
                subul.append(createLeftSidebarDropdown(subItem, isRedirect));
            } else {
                subul.append(createRedirect(subItem, isRedirect));
            }
        });
        return $('<li><a href="#' + id + '" aria-expanded="false" data-toggle="collapse"><i class="' + item.iconClass + '"></i><span class="translate" translateFor="menu.' + item.name + '"></span></a></li>').append(subul);
    }

    function createTopSidebarDropdown(item, isRedirect) {
        var id = "dropdown-" + item.name;
        var subul = $('<ul class="dropdown-menu" aria-labelledby="' + id + '"></ul>');
        $.each(item.childs, function (subI, subItem) {
            if (subItem.childs != undefined && subItem.childs != null) {
                subul.append(createTopSidebarDropdown(subItem, isRedirect));
            } else {
                subul.append(createRedirect(subItem, isRedirect));
            }
        });
        return $('<li class="dropdown"></li>').append($('<a class="dropdown-toggle"  href="javascript:void(0)" id="' + id + '" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"><i class="' + item.iconClass + '"></i><span class="translate" translateFor="menu.' + item.name + '"></span></a>')).append(subul);
    }

    function createRedirect(item, isRedirect) {
        var li = $('<li id="' + item.name + '"></li>');
        isRedirect === true && item.default && redirect(item.name);
        return li.append($('<a href="javascript:void(0);"><i class="' + item.iconClass + '"></i><span class="translate" translateFor="menu.' + item.name + '"></span></a>').on('click', function (e) {
            e.preventDefault();
            redirect(item.name);
        }));
    }

    function handleOffsidebar() {
        var langZhSwitchBtn = $('.lang-zh-switch-btn');
        var langEnSwitchBtn = $('.lang-en-switch-btn');
        if (getLang() == 'zh') {
            langZhSwitchBtn.addClass('switch-checked');
        } else {
            langEnSwitchBtn.addClass('switch-checked');
        }
        var themeSwitchBtn = $('.theme-switch-btn');
        if (lightUp) {
            themeSwitchBtn.addClass('switch-checked');
            themeSwitchBtn.find('span').attr('translateValue', 'lightUp').addClass(getLang());
        } else {
            themeSwitchBtn.find('span').attr('translateValue', 'lightOff').addClass(getLang());
        }
        var cbLayoutLeft = $('#cb-layout-left');
        var cbLayoutTop = $('#cb-layout-top');
        var imgLayoutLeftDisabled = $('.img-layout-disabled.layout-left');
        var imgLayoutTopDisabled = $('.img-layout-disabled.layout-top');
        if (layout == 'left') {
            cbLayoutLeft.attr('checked', true);
            imgLayoutLeftDisabled.css('z-index', 999);
            imgLayoutTopDisabled.css('z-index', 9);
        } else {
            cbLayoutTop.attr('checked', true);
            imgLayoutLeftDisabled.css('z-index', 9);
            imgLayoutTopDisabled.css('z-index', 999);
        }
        translate($(".off-sidebar"));
        langZhSwitchBtn.on("click", function () {
            changeLang(langZhSwitchBtn, langEnSwitchBtn, 'zh', 'en');
        });
        langEnSwitchBtn.on("click", function () {
            changeLang(langEnSwitchBtn, langZhSwitchBtn, 'en', 'zh');
        });
        themeSwitchBtn.on("click", function () {
            themeSwitchBtn.addClass('switch-disabled');
            if (themeSwitchBtn.hasClass('switch-checked')) {
                themeSwitchBtn.removeClass('switch-checked');
                translate(themeSwitchBtn.find('span').attr('translateValue', 'lightOff'));
                $('#baseCss').attr('href', '/webjars/css/base-dark.min.css');
            } else {
                themeSwitchBtn.addClass('switch-checked');
                translate(themeSwitchBtn.find('span').attr('translateValue', 'lightUp'));
                $('#baseCss').attr('href', '/webjars/css/base.min.css');
            }
            themeSwitchBtn.removeClass('switch-disabled');
        });
        var lock = 0;
        cbLayoutLeft.on('change', function () {
            if (lock > 0) {
                lock--;
                return;
            }
            imgLayoutLeftDisabled.css('z-index', 999);
            imgLayoutTopDisabled.css('z-index', 999);
            var layoutChange = false;
            var checked = $(this)[0].checked;
            if (checked && layout == 'top') {
                layout = 'left';
                layoutChange = true;
            } else if ((!checked) && layout == 'left') {
                layout = 'top';
                layoutChange = true;
            }
            if (layoutChange) {
                loadPageHeader();
                loadPageSidebar(false);
            }
            imgLayoutLeftDisabled.css('z-index', checked ? 999 : 9);
            imgLayoutTopDisabled.css('z-index', checked ? 9 : 999);
            lock++;
            $('#label-cb-layout-top').click();
        });
        cbLayoutTop.on('change', function () {
            if (lock > 0) {
                lock--;
                return;
            }
            imgLayoutLeftDisabled.css('z-index', 999);
            imgLayoutTopDisabled.css('z-index', 999);
            var layoutChange = false;
            var checked = $(this)[0].checked;
            if (checked && layout == 'left') {
                layout = 'top';
                layoutChange = true;
            } else if ((!checked) && layout == 'top') {
                layout = 'left';
                layoutChange = true;
            }
            if (layoutChange) {
                loadPageHeader();
                loadPageSidebar(false);
            }
            imgLayoutLeftDisabled.css('z-index', checked ? 9 : 999);
            imgLayoutTopDisabled.css('z-index', checked ? 999 : 9);
            lock++;
            $('#label-cb-layout-left').click();
        });
    }
})(jQuery);